/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package TransmissionPort;

import DataTypes.AutoDiaryDataTypes;
import DataTypes.AutoDiaryDataTypes.PrimaryActivity;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import reasoner.BasicActivitiesAcce;

/**
 *
 * @author thang
 * read data from text files then insert to db
 */
public class FileSourceHandler {
    private static Scanner is = null;
    private static final String PRIMARY_ACTIVITIES_FILE_NAME = "/home/thang/Study/Projects/AutoDiaryStore/DataFiles/activities.txt";
    private static final String GPS_DATA_FILE_NAME = "/home/thang/Study/Projects/AutoDiaryStore/DataFiles/gpsData.txt";
    //private static final String ACCE_DATA_FILE_NAME = "/home/thang/Study/Projects/AutoDiaryStore/DataFiles/acceData.txt";
    private static final String ACCE_DATA_FILE_NAME = "F:/E/study/autoDiaryData/DrFei/toImport/acceData.txt";
    
    private static final int    GOOGLE_INTERVAL = 2000; //ms = 2s
    private static final String DEVICE_ID = "samGIIFei";
        
    // for run in window ----------------------------------------------------
    //for storing activities
    private static final String WIN_PRIMARY_ACTIVITIES_FILE_NAME = "F:/E/study/autoDiaryData/DrFei/toImport/activities.txt";
    private static PrintWriter os = null;
    // end of for run in window ----------------------------------------------------
            
    // pre process, recognize basic activities
    private static BasicActivitiesAcce basicReasoner = null;

    public static void WinFileHandler(){
        basicReasoner = new BasicActivitiesAcce();            
        os = mylib.FileHandler.openFileToWrite(WIN_PRIMARY_ACTIVITIES_FILE_NAME);        
        // get accelerometer Data from text file
        openFile(ACCE_DATA_FILE_NAME);
        getData(ACCE_DATA_FILE_NAME);
        closeFileWin();        
    }
    
    // open data files
    // get data from files
    // store in db
    // close data files
    public static void FileHandler(){
        // connect data base
        //if ( !DbPort.Declare.connectDb ) {
            DbPort.ConnectionManager.connectDb();
        //}
        
        // get accelerometer Data from text file
        openFile(ACCE_DATA_FILE_NAME);
        getData(ACCE_DATA_FILE_NAME);
        closeFile();        

        // get primitive activities from tex file
        openFile(PRIMARY_ACTIVITIES_FILE_NAME);
        getData(PRIMARY_ACTIVITIES_FILE_NAME);
        closeFile();
        
        // get gpsData from text file
        openFile(GPS_DATA_FILE_NAME);
        getData(GPS_DATA_FILE_NAME);
        closeFile();        
        
        // close database
        DbPort.ConnectionManager.disconnectDb();
    }
    
    public static void openFile(String fileName){
        try{
            is = new Scanner(new FileInputStream(fileName));
        }
        catch(FileNotFoundException e){
            System.out.println("Load file error");
            System.exit(0);
        }
    }

    public static void closeFileWin(){
        is.close();
        os.close();
    }
    
    public static void closeFile(){
        is.close();
    }
    
    // get every line from is
    public static void getData(String fileName){
        String line = "";
        
        if ( fileName.equalsIgnoreCase(ACCE_DATA_FILE_NAME) ){
            while ( is.hasNextLine() ){
                line = is.nextLine();
                gotAccelerometerData(line);
            }
        }

        if ( fileName.equalsIgnoreCase(PRIMARY_ACTIVITIES_FILE_NAME) ){
            while ( is.hasNextLine() ){
                line = is.nextLine();
                gotPrimaryActivity(line);
            }
        }
        
        // this block should  be in separate thread
        if ( fileName.equalsIgnoreCase(GPS_DATA_FILE_NAME) ){
            while ( is.hasNextLine() ){
                line = is.nextLine();
                gotGpsData(line);
                
                // sleep otherwise google block
                try {
                    Thread.sleep(GOOGLE_INTERVAL);
                } catch (InterruptedException e) {
                }
            }
        }

    }
    
    public static void gotAccelerometerData(String line){
        // check null and trim.
        if ( line == null ){ return; }
        line = line.trim();
        if ( line.length() == 0){ return; }

        String[] arrRow = line.split("\\s");

        DataTypes.AutoDiaryDataTypes.Accelerometer acce = new DataTypes.AutoDiaryDataTypes.Accelerometer();
        
        // put in data package
        acce.setAcceX( Float.parseFloat(arrRow[0]) );
        acce.setAcceY( Float.parseFloat(arrRow[1]) );
        acce.setAcceZ( Float.parseFloat(arrRow[2]) );
        acce.setCpuTimeStamp( Long.parseLong(arrRow[3]) );
        acce.setSensorTimeStamp( Long.parseLong(arrRow[4]) );
        
        // recognize basic activities
        PrimaryActivity basicAct = basicReasoner.processAccelerometerData(acce);
        
        // put in db
        if( basicAct != null ) {
            writeToFile(basicAct);
            //DbPort.DataReceiver.receiveData(basicAct);
        }
    }
    
    // write activity to text file
    public static void writeToFile(PrimaryActivity basicAct){
        String mData = "";
        // code, sensorTimeStamp
        mData += basicAct.getActivityCode() + "\t" + basicAct.getSensorTimeStamp();
    	os.println(mData);
    }
    
    public static void gotPrimaryActivity(String line){
        // check null and trim.
        if ( line == null ){ return; }
        line = line.trim();
        if ( line.length() == 0){ return; }

        String[] arrRow = line.split("\\s");

        DataTypes.AutoDiaryDataTypes.PrimaryActivity pa = new DataTypes.AutoDiaryDataTypes.PrimaryActivity();
        
        pa.setDevice_id(DEVICE_ID);
        pa.setActivityCode(arrRow[0]);
        pa.setSensorTimeStamp( Long.parseLong(arrRow[1]) );
        DbPort.DataReceiver.receiveData(pa);
    }

    public static void gotGpsData(String line){
        // check null and trim.
        if ( line == null ){ return; }
        line = line.trim();
        if ( line.length() == 0){ return; }

        String[] arrRow = line.split("\\s");
        
        DataTypes.AutoDiaryDataTypes.Gps g = new DataTypes.AutoDiaryDataTypes.Gps();
        
        g.setDevice_id(DEVICE_ID);
        g.setGpsLat(Double.parseDouble(arrRow[0]));
        g.setGpsLong(Double.parseDouble(arrRow[1]));
        g.setGpsAccuracy(Float.parseFloat( arrRow[2]) );
        g.setGpsSpeed(Float.parseFloat(arrRow[3]));
        g.setGpsTime(Long.parseLong(arrRow[4]));
                
        long gpsData_id = DbPort.DataReceiver.receiveData(g);
        
        // set initial radius equal to accuracy
        int radius = Math.round( g.getGpsAccuracy() );
        
        try {
            FillSecondaryData.fill(gpsData_id, g.getGpsLat(), g.getGpsLong(), radius);
        } catch (IOException ex) {
            Logger.getLogger(FileSourceHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
        
    }

}
